const express = require('express');
const router = express.Router();
const con = require("../db");
const con2 = require("../db/mysql");
router.get('/', (req, res, next) => {
  const { page, limit } = req.query;
  con.query(`SELECT * FROM menu ORDER BY id DESC LIMIT ${limit} OFFSET ${(page - 1) * limit}; SELECT COUNT(*) AS total FROM menu`, (err, result) => {
    if (err) {
      console.error("Error executing query:", err);
      res.status(500).json({
        msg: "查询失败",
        code: 500
      });
      return;
    }

    res.json({
      msg: "查询成功",
      code: 200,
      data: result[0],
      total: result[1][0].total
    });
  });
});

router.post('/', async (req, res, next) => {
  const { body } = req;
  try {
    const result = await con2.query(`INSERT INTO menu (label, icon, path,parent) VALUES (?, ?, ?,?)`, [body.label, body.icon, body.path,body.parent]);
    if (result.affectedRows === 1) {
      res.json({
        msg: "添加成功",
        code: 200
      });
    } else {
      res.json({
        msg: "添加失败",
        code: 500
      });
    }
  } catch (e) {
    next(e); // 推荐将错误传递给 Express 的错误处理中间件
  }
});


router.delete('/:id', (req, res) => {
  const { id } = req.params;
  con.query(`DELETE FROM menu WHERE id=?`, id, (err, result) => {
    if (err) throw err;

    if (result.affectedRows === 1) {
      res.json({
        msg: "删除成功",
        code: 200
      });
    } else {
      res.json({
        msg: "删除失败",
        code: 500
      });
    }
  });
});
// router.put('', async(req, res) => {
  
//   const { label, icon,path,parent } = req.body;
  
//   const result2=await con.query(`UPDATE menu SET label=?,icon=?,path=?,parent=? WHERE id=?`, [label, icon,path,parent, id], (err, result) => {
//     if (err) throw err;

//     if (result.affectedRows === 1) {
//       res.json({
//         msg: "更新成功",
//         code: 200
//       });
//     } else {
//       res.json({
//         msg: "更新失败",
//         code: 500
//       });
//     }
//   });
  
// });

router.put('/:id', async(req, res) => {
  const { id } = req.params;
  const { label, icon,path,parent } = req.body;
  try{const result1=await con2.query(`SELECT * FROM menu WHERE label=? AND id !=?`, [label, id]);
  if(result1.length){
    res.json({
      msg: "编辑失败",
      code: 500
    });
  }else{
    const result2=await con2.query(`UPDATE menu SET label=?,icon=?,path=?,parent=? WHERE id=?`, [label, icon,path,parent, id] );
    
      if (err) throw err;
  
      if (result2.changeRows === 1) {
        res.json({
          msg: "更新成功",
          code: 200
        });
      } else {
        res.json({
          msg: "更新失败",
          code: 500
        });
      }
    
  }}catch(e){
    console.log(e);
  }
  
});

module.exports = router;
